﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace HttpConnection
{
    public static class UrlParser
    {
        public static bool ValidateUrl(string url, out Uri value)
        {
            List<Regex> validationRules = new List<Regex>()
            {
                new Regex(@"[a-zA-Z]{3,}://[a-zA-Z0-9\.]+/*[a-zA-Z0-9/\\%_.]*\?*[a-zA-Z0-9/\\%_.=&amp;]*", RegexOptions.IgnoreCase),
                new Regex(@"^[a-z]+([a-z0-9-]*[a-z0-9]+)?(\.([a-z]+([a-z0-9-]*[a-z0-9]+)?)+)*$", RegexOptions.IgnoreCase)
            };

            value = null;

            bool isValidUrl = false;
            foreach (var rule in validationRules)
            {
                isValidUrl = rule.IsMatch(url);

                if (isValidUrl)
                {
                    break;
                }
                else
                {
                    return false;
                }
            }

            Uri uri;
            if (Uri.TryCreate(url, UriKind.Absolute, out uri))
            {
                value = uri;
                return true;
            }

            return false;
        }
    }
}
